package org.jetnuke.modules.news;

import java.util.Date;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.util.concurrent.executor.QueuedExecutor;
import net.jforum.util.mail.EmailException;
import net.jforum.util.mail.EmailSenderTask;
import net.jforum.util.mail.Spammer;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.MainConfig;
import org.jetnuke.entities.Stories;
import org.jetnuke.util.JetUtil;

public class SendFriend implements IAction {

	String fmail,fname,ymail,yname;
	int id;
	public void setId(int id) {
		this.id = id;
	}
	public void setFmail(String fmail) {
		this.fmail = fmail;
	}
	public void setFname(String fname) {
		this.fname = fname;
	}
	public void setYmail(String ymail) {
		this.ymail = ymail;
	}
	public void setYname(String yname) {
		this.yname = yname;
	}
	/* (non-Javadoc)
	 * @see org.jetnuke.common.IAction#exec(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.apache.velocity.VelocityContext, org.jetnuke.common.IModuleInfo, java.lang.String, org.jetnuke.common.IUserInfo, org.jetnuke.common.IAdminInfo)
	 */
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		Stories st=DataAccessDriver.getInst().newStoriesDAO().retrieveByPK(id);
		MainConfig config = (MainConfig) request.getAttribute("MAIN_CONFIG");
		String sitename=config.getSITENAME();
		String nukeUrl=config.getNUKEURL();
		//Session mailSession = (Session)request.getSession(true).getServletContext().getAttribute("mailSession");
		
		//Message message = new MimeMessage(mailSession);
		
		//message.setRecipient(Message.RecipientType.TO, new InternetAddress(
		//		fmail));
		//message.setFrom(new InternetAddress(ymail,yname));
		String interesting=(String)vc.get("_INTERESTING");
		String subject=interesting+ " "+sitename;
		//message.setSubject(subject);
		String hello=(String)vc.get("_HELLO");
		String your_friend=(String)vc.get("_YOURFRIEND");
		String considered=(String)vc.get("_CONSIDERED");
		if(nukeUrl.endsWith("/"))
			nukeUrl=nukeUrl.substring(0,nukeUrl.length()-1);
		String text= hello+" "+ fname+":\n\n"+your_friend+" "+yname+ " "+considered+" \n\n"+st.getTITLE()+"\n\nURL: " +nukeUrl+"/do/news/story?id="+id;

		
		QueuedExecutor.getInstance().execute(
				new EmailSenderTask(
						new SendFriendSpammer(subject, text,fmail,yname,ymail)));
		
		//message.setText(text);
		//message.setHeader("X-Mailer","Java");
		//Transport.send(message);
		
		
		JetUtil.redirect(vc,response,request.getContextPath()+"/do/news/sent");
		return null;
	}
	class SendFriendSpammer extends Spammer{
		String subject1,  txt,  senderMail,  authorName, recipient;
		MimeMessage message;
		public SendFriendSpammer(String subject1, String txt, String senderMail, String authorName,String recipient){
			this.subject1=subject1;
			this.txt=txt;
			this.senderMail=senderMail;
			this.authorName=authorName;
			this.recipient=recipient;
			
			message=new MimeMessage(Spammer.getSession());
			
			try {
				InternetAddress[] recipients = new InternetAddress[1];
				recipients[0]=new InternetAddress(recipient);
				
				String charset = SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET);

				this.message.setSentDate(new Date());
				InternetAddress ia = new InternetAddress(senderMail);
				ia.setPersonal(authorName);
				
				this.message.setFrom(ia);
				this.message.setSubject(subject1, charset);
				
				
				this.message.setContent(txt, "text/html; charset=" + charset);
				
				this.message.setRecipients(Message.RecipientType.TO, recipients);
			}
			catch (Exception e) {
				//logger.warn("EmailException: "+ e);
				throw new EmailException(e);
			}
		}
		public boolean dispatchMessages() throws Exception {
			
			String username = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_USERNAME);
			String password = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_PASSWORD);
			
			if (SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_AUTH)) {
				if (username != null && !username.equals("") && password != null && !password.equals("")) {
					Transport transport = Spammer.getSession().getTransport("smtp");
					
					try {
						transport.connect(SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_HOST), username, password);
					}
					catch (MessagingException e) {
						throw new EmailException("Could not connect to the mail server", e);
					}
					
					if (transport.isConnected()) {
						Address[] addresses = message.getAllRecipients();
						for (int i = 0; i < addresses.length; i++) {
							// Tricks and tricks
							message.setRecipient(Message.RecipientType.TO, addresses[i]);
							transport.sendMessage(message, new Address[] { addresses[i] });
						}
					}
				}
			}
			else {
				Address[] addresses = message.getAllRecipients();
				for (int i = 0; i < addresses.length; i++) {
					message.setRecipient(Message.RecipientType.TO, addresses[i]);
					Transport.send(message, new Address[] { addresses[i] });
				}
			}
			
			return true;
		}
		
	}
}
